package com.foolishbird.sdk.ui.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.bean.WindowMessage;
import com.foolishbird.sdk.utils.ResUtils;
import com.squareup.picasso.Picasso;


public final class FloatWindowView extends FrameLayout {

    private static final long HIDE_WINDOW_VIEW_DELAY_MILLIS = 15000;
    private static final long HIDE_WINDOW_VIEW_RESUME_MILLIS = 10000;

    private static final String PROPERTY_TRANSLATION_X = "translationX";

    private final int mLeftIconResId;
    private final int mRightIconResId;
    private final int mIconResId;

    private ImageView mFloatIcon;
    private FrameLayout mWindowMessageParentView;

    private OnFloatWindowClickListener listener;

    private int mCurrentGravity = Gravity.NO_GRAVITY;
    private volatile boolean cancelAutoHide = false;

    private long mLastResumeAutoHideTime;
    private View mCurrentClickView;
    private String iconType ="fanli,hongbao,kefu,mianfei";

    public FloatWindowView(Context context) {
        this(context, null);
    }

    public FloatWindowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatWindowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        int resId = ResUtils.getLayoutIdentifier(context, "wan_customview_float_window");
        int iconResId = ResUtils.getViewIdentifier(context, "customview_float_window_icon");
        int windowMessageResId = ResUtils.getViewIdentifier(context, "customview_float_window_message");
//        String type = HttpEngineApi.getInstance().getEngineConduits().readFloatWindowType();
//        if(!TextUtils.isEmpty(type)&&iconType.contains(type)){
//                mLeftIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window_left_"+type);
//                mRightIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window_right_"+type);
//                mIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window_"+type);
//        }else {
            mLeftIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window_left");
            mRightIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window_right");
            mIconResId = ResUtils.getDrawableIdentifier(context, "wan_icon_float_window");
//        }


        View view = LayoutInflater.from(context).inflate(resId, this);
        mFloatIcon = view.findViewById(iconResId);
        mFloatIcon.setImageResource(mIconResId);
        mWindowMessageParentView = view.findViewById(windowMessageResId);

        mFloatIcon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onWindowClick(view);
                }
            }
        });
    }

    @Override
    public void setOnTouchListener(OnTouchListener listener) {
        super.setOnTouchListener(listener);
        mFloatIcon.setOnTouchListener(listener);
    }

    public final boolean isSupportGesture() {
        return mFloatIcon != null && mFloatIcon.getVisibility() == VISIBLE;
    }

    public void setOnFloatWindowClickListener(OnFloatWindowClickListener listener) {
        this.listener = listener;
    }

    public void setImageResource() {
        if (mWindowMessageParentView != null && mWindowMessageParentView.getChildCount() > 0) {
            setWindowMessageViewVisible(true);
        } else {
            if (mFloatIcon != null) {
                setAlpha(1.0f);
                mFloatIcon.setImageResource(mIconResId);
            }
        }
    }

    public void setLeftImageResource() {
        if (mFloatIcon != null) {
            mFloatIcon.setImageResource(mLeftIconResId);
            mCurrentGravity = Gravity.LEFT;
        }
    }

    public void setRightImageResource() {
        if (mFloatIcon != null) {
            mFloatIcon.setImageResource(mRightIconResId);
            mCurrentGravity = Gravity.RIGHT;
        }
    }

    private void startWindowBallAnimator() {
        ValueAnimator animator = ValueAnimator.ofInt(0, 255);
        animator.setDuration(500);
        animator.setStartDelay(500);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mFloatIcon.setImageAlpha((Integer) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    public final void setWindowGravity(int gravity) {
        this.mCurrentGravity = gravity;
    }

    public void setCancelAutoHide(boolean cancel) {
        this.mLastResumeAutoHideTime = System.currentTimeMillis();
        this.cancelAutoHide = cancel;
        if(mCurrentClickView != null){
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWindowMessageParentView.removeView(mCurrentClickView);
                    mCurrentClickView = null;
                }
            }, 500);
        }
    }

    public void setWindowMessageData(WindowMessage message) {
        if (message != null) {
            setWindowMessageViewVisible(true);
            mWindowMessageParentView.setLayoutTransition(createCustomLayoutAnimations());

            final int childCount = mWindowMessageParentView.getChildCount();
            final int width = ViewGroup.LayoutParams.WRAP_CONTENT;
            final int height = ResUtils.dip2px(getContext(), 45);
            final int margins = ResUtils.dip2px(getContext(), 5);
            final int marginsTop = (childCount * (height + margins + margins)) + margins;

            LayoutParams layoutParams = new LayoutParams(width, height);
            layoutParams.setMargins(0, marginsTop, 0, margins);
            if (mCurrentGravity == Gravity.RIGHT) {
                layoutParams.gravity = Gravity.END;
            } else {
                layoutParams.gravity = Gravity.START;
            }
            View windowMessageView = createWindowMessageView(message);
            mWindowMessageParentView.addView(windowMessageView, layoutParams);

            postDelayed(new HideWindowMessageRunnable(windowMessageView), HIDE_WINDOW_VIEW_DELAY_MILLIS);
        }
    }

    private void setWindowMessageViewVisible(boolean visible) {
        if (visible) {
            if (listener != null) {
                if (mFloatIcon.getVisibility() != GONE) {
                    listener.onWindowBallVisibleChanged(false);
                }
            }
            mFloatIcon.setVisibility(GONE);
        } else {
            if (listener != null) {
                if (mFloatIcon.getVisibility() != VISIBLE) {
                    listener.onWindowBallVisibleChanged(true);
                }
            }
            mFloatIcon.setImageAlpha(0);
            mFloatIcon.setVisibility(VISIBLE);
            startWindowBallAnimator();
        }
        mWindowMessageParentView.setVisibility(visible ? VISIBLE : GONE);
    }

    private void checkWindowMessageViewStatus() {
        int childCount = mWindowMessageParentView.getChildCount();
        setWindowMessageViewVisible(childCount > 0);
    }

    private LayoutTransition createCustomLayoutAnimations() {
        LayoutTransition layoutTransition = new LayoutTransition();

        final int width = ResUtils.dip2px(getContext(), 220);
        PropertyValuesHolder pvhInTransX;
        PropertyValuesHolder pvhOutTransX;
        if (mCurrentGravity == Gravity.RIGHT) {
            pvhInTransX = PropertyValuesHolder.ofFloat(PROPERTY_TRANSLATION_X, width, 0f);
            pvhOutTransX = PropertyValuesHolder.ofFloat(PROPERTY_TRANSLATION_X, 0, width);
        } else {
            pvhInTransX = PropertyValuesHolder.ofFloat(PROPERTY_TRANSLATION_X, -width, 0f);
            pvhOutTransX = PropertyValuesHolder.ofFloat(PROPERTY_TRANSLATION_X, 0, -width);
        }

        // 动画：APPEARING
        // view出现时 view自身的动画效果
        PropertyValuesHolder[] appearingPvh = {pvhInTransX};
        ObjectAnimator appearingAnimator = ObjectAnimator.ofPropertyValuesHolder(this, appearingPvh);
        appearingAnimator.setDuration(layoutTransition.getDuration(LayoutTransition.APPEARING));
        layoutTransition.setAnimator(LayoutTransition.APPEARING, appearingAnimator);
        layoutTransition.setDuration(LayoutTransition.APPEARING, 800);
        layoutTransition.setInterpolator(LayoutTransition.APPEARING, new AccelerateDecelerateInterpolator());

        // 动画：DISAPPEARING
        // view 消失时，view自身的动画效果
        PropertyValuesHolder[] disappearingPvh = {pvhOutTransX};
        ObjectAnimator disappearingAnimator = ObjectAnimator.ofPropertyValuesHolder(this, disappearingPvh);
        disappearingAnimator.setDuration(layoutTransition.getDuration(LayoutTransition.DISAPPEARING));
        layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, disappearingAnimator);
        layoutTransition.setDuration(LayoutTransition.DISAPPEARING, 800);
        layoutTransition.setInterpolator(LayoutTransition.DISAPPEARING, new AccelerateDecelerateInterpolator());
        disappearingAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                checkWindowMessageViewStatus();
            }
        });

        return layoutTransition;
    }

    private View createWindowMessageView(WindowMessage message) {
        //create parent view
        int backgroundResId = ResUtils.getDrawableIdentifier(getContext(), "hnssn_float_window_message_background");
//        int imageResId = ResUtils.getDrawableIdentifier(getContext(), "wan_icon_float_window");
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setBackgroundResource(backgroundResId);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setOnClickListener(new OnWindowMessageClickListener(message));
        linearLayout.setSelected(mCurrentGravity == Gravity.RIGHT);

        //create icon view
        ImageView iconImageView = new ImageView(getContext());
        iconImageView.setImageResource(mIconResId);
        iconImageView.setBackgroundColor(Color.TRANSPARENT);
        Picasso.with(getContext()).load(message.getIcon()).error(mIconResId).into(iconImageView);

        final int widthOrHeight = ResUtils.dip2px(getContext(), 30);
        final int margins = ResUtils.dip2px(getContext(), 10);
        LinearLayout.LayoutParams iconLayoutParams = new LinearLayout.LayoutParams(widthOrHeight, widthOrHeight);
        iconLayoutParams.gravity = Gravity.CENTER_VERTICAL;
        iconLayoutParams.setMargins(margins, margins, margins, margins);
        linearLayout.addView(iconImageView, iconLayoutParams);

        //create text view
        TextView messageTextView = new TextView(getContext());
        messageTextView.setText(message.getContent());
        messageTextView.setTextColor(0xFF333333);
        messageTextView.setTextSize(12);
        messageTextView.setMaxLines(2);
        messageTextView.setEllipsize(TextUtils.TruncateAt.END);
        messageTextView.setMaxWidth(ResUtils.dip2px(getContext(), 150));
        messageTextView.setMinWidth(ResUtils.dip2px(getContext(), 100));

        final int textWidthOrHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
        LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(textWidthOrHeight, textWidthOrHeight);
        textLayoutParams.gravity = Gravity.CENTER_VERTICAL;
        linearLayout.addView(messageTextView, textLayoutParams);

        //create close view
        int imageCloseResId = ResUtils.getDrawableIdentifier(getContext(), "hnssn_icon_window_close");
        final int padding = ResUtils.dip2px(getContext(), 15);
        ImageView closeImageView = new ImageView(getContext());
        closeImageView.setImageResource(imageCloseResId);
        closeImageView.setPadding(padding, padding, padding, padding);
        closeImageView.setBackgroundColor(Color.TRANSPARENT);
        closeImageView.setOnClickListener(new OnCloseClickListener());

        final int closeWidthOrHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
        LinearLayout.LayoutParams closeLayoutParams = new LinearLayout.LayoutParams(closeWidthOrHeight, closeWidthOrHeight);
        closeLayoutParams.gravity = Gravity.CENTER_VERTICAL;
        linearLayout.addView(closeImageView, closeLayoutParams);

        return linearLayout;
    }

    public interface OnFloatWindowClickListener {

        void onWindowClick(View view);

        void onWindowMessageClick(View view, WindowMessage message);

        void onWindowBallVisibleChanged(boolean visible);

    }

    private final class OnCloseClickListener implements OnClickListener {

        @Override
        public void onClick(View view) {
            ViewParent parent = view.getParent();
            if (parent instanceof View) {
                mWindowMessageParentView.removeView((View) parent);
            }
        }
    }

    private final class OnWindowMessageClickListener implements OnClickListener {

        private final WindowMessage message;

        public OnWindowMessageClickListener(WindowMessage message) {
            this.message = message;
        }

        @Override
        public void onClick(View view) {
            cancelAutoHide = true;
            mCurrentClickView = view;
            if (listener != null) {
                listener.onWindowMessageClick(view, message);
            }
        }
    }

    private final class HideWindowMessageRunnable implements Runnable {

        private final View removeView;

        public HideWindowMessageRunnable(View removeView) {
            this.removeView = removeView;
        }

        @Override
        public void run() {
            if (!cancelAutoHide) {
                final long currentTime = System.currentTimeMillis();
                final long intervalTime = Math.abs(currentTime - mLastResumeAutoHideTime);
                if (intervalTime > HIDE_WINDOW_VIEW_RESUME_MILLIS) {
                    mWindowMessageParentView.removeView(removeView);
                } else {
                    final long leftoverTime = Math.abs(HIDE_WINDOW_VIEW_DELAY_MILLIS - intervalTime);
                    postDelayed(new HideWindowMessageRunnable(removeView), leftoverTime);
                }
            } else {
                postDelayed(new HideWindowMessageRunnable(removeView), HIDE_WINDOW_VIEW_DELAY_MILLIS);
            }
        }
    }

}
